package com.ocom.exposeapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.ExposeApiUrl;
import com.ocom.common.entity.company.EntityComDockApi;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.icbcyxt.IcbcYxtResultEnum;
import com.ocom.common.request.company.GetReplyApiParaRequest;
import com.ocom.common.request.exposeapi.icbcyxt.BalanceRequest;
import com.ocom.common.request.exposeapi.icbcyxt.RechargeRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.SM3;
import com.ocom.common.vo.human.UserInfoVo;
import com.ocom.common.vo.pay.UpdateListRechargeVo;
import com.ocom.exposeapi.feign.CompanyClientService;
import com.ocom.exposeapi.feign.HumanFeignService;
import com.ocom.exposeapi.feign.PayConfigClientService;
import com.ocom.exposeapi.vo.icbcyxt.IcbcYxtBalanceResultVo;
import com.ocom.exposeapi.vo.icbcyxt.IcbcYxtRechargeResultVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 工行银校通
 * @Author: lvwenxiang
 * @Date: 2023/4/26
 **/
@Slf4j
@RestController
public class ICBCYxtController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CompanyClientService companyClientService;

    @Autowired
    private HumanFeignService humanFeignService;

    @Autowired
    private PayConfigClientService payConfigClientService;


    @PostMapping(ExposeApiUrl.URL_ExposeApi_IcbcyxtRecharge)
    public IcbcYxtRechargeResultVo recharge(@Validated @RequestBody RechargeRequest request, BindingResult bindingResult) {
        EntityComDockApi entityComDockApi = new EntityComDockApi();
        try {

            logger.info("===================账号充值===================");
            logger.info("===================请求参数===================" + request.toString());

            String resultCode = IcbcYxtResultEnum.Err_9999.getKey();

            //1、调用单位微服务6.21获取响应接口参数getReplyApiPara。
            Result result = getReplyApiPara(request.getMerchantID(), "icbcyxt", "icbcyxt#recharge");

            if (null == result) {
                logger.info("===================查询getReplyApiPara为空===================");
                return setRechargeResult(resultCode, entityComDockApi.getKey());
            } else if (result.getCode() != 200) {
                logger.info("===================查询getReplyApiPara失败===================");
                resultCode = getSwitch(result.getCode(), resultCode);
                return setRechargeResult(resultCode, entityComDockApi.getKey());
            }

            entityComDockApi = JSON.parseObject(JSON.toJSONString(result.getData()), EntityComDockApi.class);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(request.getVersionId())
                    .append(request.getClientID())
                    .append(request.getMerchantID())
                    .append(request.getICCID())
                    .append(request.getOrderId())
                    .append(request.getTranSeq())
                    .append(request.getAmount())
                    .append(request.getOrderDate())
                    .append(entityComDockApi.getKey());

            logger.info("===================SM3原始值===================" + stringBuilder.toString());
            //SM3加密
            String sign = SM3.encrypt(stringBuilder.toString());
            logger.info("===================rechargeSign：【{}】===================",sign);

            //验签
            if (!sign.equals(request.getMAC())) {
                logger.info("===================验签失败！MAC：【{}】===================",request.getMAC());
                return setRechargeResult(IcbcYxtResultEnum.Err_0002.getKey(), entityComDockApi.getKey());
            }

            //2、调用部门人事微服务2.2.1获取人员列表personnel/getPersonInfo
            logger.info("===================查询getPersonInfo===================");
            Result personInfoResult = getPersonInfo(entityComDockApi.getComId(), request.getICCID());
            if (null == personInfoResult) {
                logger.info("===================查询getPersonInfo为空===================");
                return setRechargeResult(resultCode, entityComDockApi.getKey());
            } else if (personInfoResult.getCode() != 200 || null == personInfoResult.getData()) {
                logger.info("===================查询getPersonInfo失败===================");
                return setRechargeResult(IcbcYxtResultEnum.Err_0202.getKey(), entityComDockApi.getKey());
            }

            EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(personInfoResult.getData()), EntityPersonnelInfo.class);

            //3、调用消费配置微服务4.1获取账号信息getXFAccount(recharge已内置调用)

            //4、调用消费配置微服务7.3个人账户充值updateListRecharge充值。
            logger.info("===================查询updateListRecharge===================");
            Result rechargeResult = updateListRecharge(entityComDockApi, entityPersonnelInfo, request);
            if (null == rechargeResult) {
                logger.info("===================查询updateListRecharge为空===================");

                return setRechargeResult(resultCode, entityComDockApi.getKey());
            } else if (rechargeResult.getCode() != 200) {
                logger.info("===================查询updateListRecharge失败===================");

                return setRechargeResult(IcbcYxtResultEnum.Err_0400.getKey(), entityComDockApi.getKey());
            }

        } catch (Exception e) {
            logger.info("===================账号充值===================");

            e.printStackTrace();
        }
        logger.info("===================账号充值完成===================");
        return setRechargeResult(IcbcYxtResultEnum.Success_Success.getKey(), entityComDockApi.getKey());
    }

    @PostMapping(ExposeApiUrl.URL_ExposeApi_IcbcyxtBalance)
    public IcbcYxtBalanceResultVo balance(@Validated @RequestBody BalanceRequest request, BindingResult bindingResult) {
        Integer amount = 0;
        EntityComDockApi entityComDockApi = new EntityComDockApi();
        try {
            logger.info("===================查询余额===================");
            logger.info("===================请求参数===================" + request.toString());

            String resultCode = IcbcYxtResultEnum.Err_9999.getKey();

            //1、调用单位微服务6.21获取响应接口参数getReplyApiPara。
            Result result = getReplyApiPara(request.getMerchantID(), "icbcyxt", "icbcyxt#balance");

            if (null == result) {
                logger.info("===================查询getReplyApiPara为空===================");
                return setBalanceResult(resultCode, "", entityComDockApi.getKey());
            } else if (result.getCode() != 200) {
                logger.info("===================查询getReplyApiPara失败===================");
                resultCode = getSwitch(result.getCode(), resultCode);
                return setBalanceResult(resultCode, "", entityComDockApi.getKey());
            }

            entityComDockApi = JSON.parseObject(JSON.toJSONString(result.getData()), EntityComDockApi.class);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(request.getVersionId())
                    .append(request.getClientID())
                    .append(request.getMerchantID())
                    .append(request.getPhoneNumber())
                    .append(request.getIccId())
                    .append(entityComDockApi.getKey());
            logger.info("===================SM3原始值===================" + stringBuilder.toString());

            //SM3加密
            String sign = SM3.encrypt(stringBuilder.toString());
            logger.info("===================BalanceSign：【{}】===================",sign);


            //验签
            if (!sign.equals(request.getMac())) {
                logger.info("===================验签失败！MAC：【{}】===================",request.getMac());
                return setBalanceResult(IcbcYxtResultEnum.Err_0002.getKey(), "", entityComDockApi.getKey());
            }

            //2、调用部门人事微服务2.2.1获取人员列表personnel/getPersonInfo
            logger.info("===================查询getPersonInfo===================");
            Result personInfoResult = getPersonInfo(entityComDockApi.getComId(), request.getIccId());
            if (null == personInfoResult) {
                logger.info("===================查询getPersonInfo为空===================");
                return setBalanceResult(resultCode, "", entityComDockApi.getKey());
            } else if (personInfoResult.getCode() != 200 || null == personInfoResult.getData()) {
                logger.info("===================查询getPersonInfo失败===================");

                return setBalanceResult(IcbcYxtResultEnum.Err_0202.getKey(), "", entityComDockApi.getKey());
            }

            EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(personInfoResult.getData()), EntityPersonnelInfo.class);

            //4、调用消费配置微服务4.1获取账号信息getXFAccount
            logger.info("===================查询getPersonInfo===================");
            Result xfAcount = payConfigClientService.GetXFAccount(entityPersonnelInfo.getComId(), Integer.valueOf(entityPersonnelInfo.getPId().toString()));
            if (xfAcount.getCode() != 200 || null == xfAcount.getData()) {
                logger.info("===================查询getPersonInfo失败===================");
                return setBalanceResult(IcbcYxtResultEnum.Err_0201.getKey(), "", entityComDockApi.getKey());
            }
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(xfAcount.getData()));

            amount = jsonObject.getIntValue("accountRechargeMoney");
        } catch (Exception e) {
            logger.info("===================查询余额失败===================");
            e.printStackTrace();
        }
        logger.info("===================查询余额成功===================：amount：" + amount.toString());
        return setBalanceResult(IcbcYxtResultEnum.Success_Success.getKey(), amount.toString(), entityComDockApi.getKey());
    }

    private String getSwitch(Integer code, String resultCode) {
        switch (code) {
            case 3101:
            case 3102:
            case 3103:
                resultCode = IcbcYxtResultEnum.Err_0100.getKey();
                break;
            case 3104:
                resultCode = IcbcYxtResultEnum.Err_0300.getKey();
                break;
        }
        return resultCode;
    }

    private IcbcYxtRechargeResultVo setRechargeResult(String resultCode,String key) {
        IcbcYxtRechargeResultVo resultVo = new IcbcYxtRechargeResultVo();

        resultVo.setResultCode(resultCode);
        resultVo.setResultMsg(IcbcYxtResultEnum.getValueByKey(resultCode));

//        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append(resultVo.getResultCode());
//        stringBuilder.append(resultVo.getResultMsg());
//        String sign = SM3.encrypt(stringBuilder.append(key).toString());
//        resultVo.setMac(sign);

        logger.info("===================响应结果===================：" + resultVo.toString());
        return resultVo;
    }

    private IcbcYxtBalanceResultVo setBalanceResult(String resultCode, String amount, String key) {
        IcbcYxtBalanceResultVo resultVo = new IcbcYxtBalanceResultVo();

        resultVo.setResultCode(resultCode);
        resultVo.setResultMsg(IcbcYxtResultEnum.getValueByKey(resultCode));
        resultVo.setAmount(amount);

//        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append(resultVo.getResultCode());
//        stringBuilder.append(resultVo.getResultMsg());
//        stringBuilder.append(resultVo.getAmount());
//        String sign = SM3.encrypt(stringBuilder.append(key).toString());
//        resultVo.setMac(sign);

        logger.info("===================响应结果===================：" + resultVo.toString());
        return resultVo;
    }

    private void setUpdateListRechargeVo(Integer typeNo, String typeName, String remark, UpdateListRechargeVo updateListRechargeVo) {
        updateListRechargeVo.setTypeNo(typeNo);
        updateListRechargeVo.setTypeName(typeName);
        updateListRechargeVo.setRemark(remark);
    }

    private Result getReplyApiPara(String comAppid, String dockCode, String dockApiCode) {
        Result result = null;
        try {
            GetReplyApiParaRequest getReplyApiParaRequest = new GetReplyApiParaRequest();
            getReplyApiParaRequest.setComAppid(comAppid);
            getReplyApiParaRequest.setDockCode(dockCode);
            getReplyApiParaRequest.setDockApiCode(dockApiCode);
            getReplyApiParaRequest.setSvrAppid(comAppid);
            getReplyApiParaRequest.setKeyType(5);
            result = companyClientService.getReplyApiPara(getReplyApiParaRequest);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }

    private Result getPersonInfo(Long comId, String code) {
        Result result = null;
        try {
            UserInfoVo userInfoVo = new UserInfoVo();
            userInfoVo.setComId(comId);
            userInfoVo.setPCode(code);
            userInfoVo.setOnlyOne(true);
            result = humanFeignService.PersonnelGetPersonInfo(userInfoVo);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }

    private Result updateListRecharge(EntityComDockApi entityComDockApi, EntityPersonnelInfo entityPersonnelInfo, RechargeRequest request) {
        Result result = null;

        try {
            UpdateListRechargeVo updateListRechargeVo = new UpdateListRechargeVo();
            updateListRechargeVo.setComId(entityComDockApi.getComId());
            updateListRechargeVo.setPId(entityPersonnelInfo.getPId());
            updateListRechargeVo.setRechargeMoney(Long.valueOf(request.getAmount()));
            updateListRechargeVo.setFrom(2);
            updateListRechargeVo.setOrderNo(request.getOrderId());
            updateListRechargeVo.setDockApiCode(entityComDockApi.getDockApiCode());
            updateListRechargeVo.setDockApiName(entityComDockApi.getApiName());

            if ("01".equals(request.getClientID())) {
                setUpdateListRechargeVo(1, "公众号", "公众号充值:" + request.getAmount() + "分", updateListRechargeVo);
            }
            if ("02".equals(request.getClientID())) {
                setUpdateListRechargeVo(2, "客户端", "客户端充值:" + request.getAmount() + "分", updateListRechargeVo);
            }
            if ("03".equals(request.getClientID())) {
                setUpdateListRechargeVo(3, "网站", "网站充值:" + request.getAmount() + "分", updateListRechargeVo);
            }
            result = payConfigClientService.UpdateListRecharge(updateListRechargeVo);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }
}
